package com.ruoyi.violate.service.impl;

import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.*;

import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.violate.domain.Gantt;
import com.ruoyi.violate.domain.ViolateTilte;
import org.apache.commons.fileupload.disk.DiskFileItem;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import com.ruoyi.violate.mapper.ViolateWordsMapper;
import com.ruoyi.violate.domain.ViolateWords;
import com.ruoyi.violate.service.IViolateWordsService;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

/**
 * 违规词汇Service业务层处理
 *
 * @author 谭拓宇
 * @date 2022-12-03
 */
@Service
public class ViolateWordsServiceImpl implements IViolateWordsService {
    @Autowired
    private ViolateWordsMapper violateWordsMapper;

    /**
     * 查询违规词汇
     *
     * @param id 违规词汇主键
     * @return 违规词汇
     */
    @Override
    public ViolateWords selectViolateWordsById(Long id) {
        return violateWordsMapper.selectViolateWordsById(id);
    }

    /**
     * 查询违规词汇列表
     *
     * @param violateWords 违规词汇
     * @return 违规词汇
     */
    @Override
    public List<ViolateWords> selectViolateWordsList(ViolateWords violateWords) {
        return violateWordsMapper.selectViolateWordsList(violateWords);
    }

    /**
     * 新增违规词汇
     *
     * @param violateWords 违规词汇
     * @return 结果
     */
    @Override
    public int insertViolateWords(ViolateWords violateWords) {
        violateWords.setCreateTime(DateUtils.getNowDate());
        violateWords.setCreateBy(SecurityUtils.getUserId() + "");
        violateWords.setLength(Long.valueOf(StringUtils.length(violateWords.getWords())));
        return violateWordsMapper.insertViolateWords(violateWords);
    }

    @Override
    public int importFile(String filePath) {
        String path = RuoYiConfig.getProfile() + filePath.substring(8, filePath.length());
        System.out.println(path);

        File file = new File(path);
        MultipartFile files = getMultipartFile(file);
        ExcelReader reader = null;
        try {
            reader = ExcelUtil.getReader(files.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        reader.addHeaderAlias("违规词", "words");
        reader.addHeaderAlias("替换词", "replaces");
        List<ViolateWords> list = reader.readAll(ViolateWords.class);
        for (ViolateWords entity : list) {
            if (StringUtils.isNotEmpty(entity.getWords())) {
                insertViolateWords(entity);
            }
        }
        return 1;
    }


    public MultipartFile getMultipartFile(File file) {
        DiskFileItem item = new DiskFileItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , file.getName()
                , (int) file.length()
                , file.getParentFile());
        try {
            OutputStream os = item.getOutputStream();
            os.write(FileUtils.readFileToByteArray(file));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return new CommonsMultipartFile(item);
    }

    /**
     * 修改违规词汇
     *
     * @param violateWords 违规词汇
     * @return 结果
     */
    @Override
    public int updateViolateWords(ViolateWords violateWords) {
        violateWords.setUpdateTime(DateUtils.getNowDate());
        violateWords.setLength(Long.valueOf(StringUtils.length(violateWords.getWords())));
        return violateWordsMapper.updateViolateWords(violateWords);
    }

    /**
     * 批量删除违规词汇
     *
     * @param ids 需要删除的违规词汇主键
     * @return 结果
     */
    @Override
    public int deleteViolateWordsByIds(Long[] ids) {
        return violateWordsMapper.deleteViolateWordsByIds(ids);
    }

    /**
     * 删除违规词汇信息
     *
     * @param id 违规词汇主键
     * @return 结果
     */
    @Override
    public int deleteViolateWordsById(Long id) {
        return violateWordsMapper.deleteViolateWordsById(id);
    }

    /**
     * 一键去重
     * @return
     */
    @Override
    public int distinctViolateWords() {
        //先对数据库里进行一次删除去重
        violateWordsMapper.distinctViolateWords() ;
        //获得words的所有的重复项
        List<ViolateWords> violateWords = violateWordsMapper.selectViolateDistinctWordsList();
        //去重逻辑，1,违规词和替换词都相同则去重
        TreeSet<ViolateWords> treeSet = new TreeSet<>(Comparator.comparing(o -> (o.getWords() + "" + o.getReplaces())));
        for (ViolateWords violateWord : violateWords) {
            treeSet.add(violateWord) ;
        }
        // 2，违规词相同优先保留删除项
        HashMap<String, ViolateWords> hashMap = new HashMap<>();
        //遍历words，让hashMap里面装需要删除的数据
        for (ViolateWords words : treeSet) {
            boolean sign = true ;
            for (Map.Entry<String, ViolateWords> entry : hashMap.entrySet()){
                //如果key相同，则将""和null的装进hashMap
                if (entry.getKey().equals(words.getWords())){
                    sign = false ;
                    //如果有相同的key,map里面的是删除，则取出来
                    if (entry!=null && entry.getValue()!=null && entry.getValue().getReplaces()!=null){
                        if (entry.getValue().getReplaces().equals("删除")){
                            entry.getValue().setId(words.getId());
                        }
                    }
                }
            }
            if (sign){
              hashMap.put(words.getWords() , words) ;
            }
        }
        //删除重复项
        for (Map.Entry<String, ViolateWords> entry : hashMap.entrySet()){
         violateWordsMapper.deleteViolateWordsById(entry.getValue().getId()) ;
        }
        return  1;
    }
}
